import torch
import torchvision
import numpy as np
import sys
sys.path.append("..") # 为了导⼊上层⽬录的d2lzh_pytorch
import d2lzh_pytorch as d2l

## maxsoft
## 获取和读取数据
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist()

#  定义输入输出参数的大小 784个像素的输入 最终结果是10分类
num_inputs = 784
num_outputs = 10

#  随机生成[784,10]size的tensor参数
w = torch.tensor(np.random.normal(0,0.01,(num_inputs,num_outputs)),dtype=torch.float)

b = torch.zeros(num_outputs,dtype=torch.float)

# 开始记录梯度
w.requires_grad_(requires_grad=True)
b.requires_grad_( requires_grad=True )


def softmax(X):
    X_exp = X.exp()
    partition = X_exp.sum(dim=1, keepdims=True)
    return  X_exp / partition #  这里应用了广播机制

#  定义模型
def net(X):
    return softmax(torch.mm(X.view((-1,num_inputs)), w) + b)  # torch.mm是矩阵相乘运算

#  交叉熵损失函数
def cross_entropy(y_hat, y):
    return - torch.log(y_hat.gather(1, y.view(-1, 1)))

#  计算分类准确率
def accuracy(y_hat, y):
    return (y_hat.argmax(dim=1) == y).float().mean().item()


num_epochs, lr = 5, 0.01

d2l.train_ch3(net(), train_iter, test_iter, cross_entropy(), num_epochs, batch_size, [w,b], lr)








